const { internalServerError } = require("../constant/error");
const {
  createComment,
  findAllComments,
  removeComment,
} = require("../service/commentService");
class CommentController {
  async create(ctx) {
    try {
      const { user_name, goods_id, content, comment_star } = ctx.request.body;

      // 检查必要参数
      if (!user_name || !goods_id || !content) {
        ctx.throw(400, "缺少必要参数");
      }

      // 创建评论
      const res = await createComment({
        user_name,
        goods_id,
        content,
        comment_star: comment_star || 5, // 默认星级为 5
      });

      ctx.body = {
        code: 0,
        msg: "添加评论成功",
        result: res,
      };
    } catch (err) {
      console.error(err);
      return ctx.app.emit("error", internalServerError, ctx);
    }
  }
  async findAll(ctx) {
    try {
      const { pageNum = 1, pageSize = 10 } = ctx.request.query;
      const res = await findAllComments(pageNum, pageSize);
      ctx.body = {
        code: 0,
        msg: "查询所有评论成功",
        result: res,
      };
    } catch (error) {
      console.error(error);
      return ctx.app.emit("error", internalServerError, ctx);
    }
  }
  async remove(ctx) {
    try {
      const id = ctx.request.params.id;
      const res = await removeComment(id);
      ctx.body = {
        code: 0,
        msg: "删除评论成功",
        result: res,
      };
    } catch (error) {
      console.error(error);
      return ctx.app.emit("error", internalServerError, ctx);
    }
  }
}
module.exports = new CommentController();
